package com.example.extra.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.extra.common.R;
import com.example.extra.entity.File;
import com.example.extra.entity.UserFile;
import com.example.extra.enums.CountryEnum;
import com.example.extra.service.IFileService;
import com.example.extra.service.IUserFileService;
import com.example.extra.vo.FileVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 文件管理接口
 * @author system
 */
@Slf4j
@Tag(name = "文件管理接口")
@RestController
@RequestMapping("/api/file")
@RequiredArgsConstructor
public class FileController {
    
    private final IFileService fileService;
    private final IUserFileService iUserFileService;

    @Value("${file.prefix}")
    private String prefix;

    @GetMapping("/list")
    @Operation(summary = "查询文件列表")
    @Parameters({@Parameter(name = "keycode", description = "专题关键编号，如俄乌战争，则传0308,0304;中间以逗号分隔")})
    public R<List<FileVo>> getFileList(@RequestParam(required = false) String keycode) {
        try {
            QueryWrapper<File> queryWrapper = new QueryWrapper<>();
            QueryWrapper<UserFile> userFileQueryWrapper = new QueryWrapper<>();
            List<File> fileList;
            Map<String, String> fileIdAndDigestMap;

            // 处理keycode参数，支持中英文逗号分隔符
            if (keycode != null && !keycode.trim().isEmpty()) {
                String[] keycodeArray = keycode.split("[,，]");
                //前端传进来俄罗斯和乌克兰的国家编码
                if(ArrayUtils.contains(keycodeArray, CountryEnum.RUSSIA.getCode())&&ArrayUtils.contains(keycodeArray, CountryEnum.UKRAINE.getCode())){
                    userFileQueryWrapper.like("keywords",CountryEnum.RUSSIA.getChineseName() ).and(i -> i.like("keywords", CountryEnum.UKRAINE.getChineseName()));
                }
                //前端传进来巴勒斯坦和以色列的国家编码
                if(ArrayUtils.contains(keycodeArray, CountryEnum.PALESTINE.getCode())&&ArrayUtils.contains(keycodeArray, CountryEnum.ISRAEL.getCode())){
                    userFileQueryWrapper.like("keywords",CountryEnum.PALESTINE.getChineseName() ).and(i -> i.like("keywords", CountryEnum.ISRAEL.getChineseName()));
                }
                //前端传进来台湾的编码
                if(ArrayUtils.contains(keycodeArray, CountryEnum.TAIWAN.getCode())){
                    userFileQueryWrapper.like("keywords",CountryEnum.TAIWAN.getChineseName());
                }
                //前端传进来印度和巴基斯坦的国家编码
                if(ArrayUtils.contains(keycodeArray, CountryEnum.INDIA.getCode())&&ArrayUtils.contains(keycodeArray, CountryEnum.PAKISTAN.getCode())){
                    userFileQueryWrapper.like("keywords",CountryEnum.INDIA.getChineseName() ).and(i -> i.like("keywords", CountryEnum.PAKISTAN.getChineseName()));
                }
                //前端传进来以色列和伊朗的国家编码
                if(ArrayUtils.contains(keycodeArray, CountryEnum.ISRAEL.getCode())&&ArrayUtils.contains(keycodeArray, CountryEnum.Iran.getCode())){
                    userFileQueryWrapper.like("keywords",CountryEnum.ISRAEL.getChineseName() ).and(i -> i.like("keywords", CountryEnum.Iran.getChineseName()));
                }
                //前端传进来军演的编码
                if(ArrayUtils.contains(keycodeArray, CountryEnum.MILITARY_EXERCISE.getCode())){
                    userFileQueryWrapper.like("keywords",CountryEnum.MILITARY_EXERCISE.getChineseName());
                }
                //前端传进来台湾舆情的编码
                if(ArrayUtils.contains(keycodeArray, CountryEnum.TAIWAN_SENTIMENT.getCode())){
                    userFileQueryWrapper.like("keywords",CountryEnum.TAIWAN_SENTIMENT.getChineseName());
                }
                //前端传进来空天领域的编码
                if(ArrayUtils.contains(keycodeArray, CountryEnum.AEROSPACE_FIELD.getCode())){
                    userFileQueryWrapper.like("keywords",CountryEnum.AEROSPACE_FIELD.getChineseName());
                }
                //前端传进来太空作战的编码
                if(ArrayUtils.contains(keycodeArray, CountryEnum.OUTER_SPACE.getCode())){
                    userFileQueryWrapper.like("keywords",CountryEnum.OUTER_SPACE.getChineseName());
                }
                //前端传进来美国新政的编码
                if(ArrayUtils.contains(keycodeArray, CountryEnum.AMERICA_NEW_DEAL.getCode())){
                    userFileQueryWrapper.like("keywords",CountryEnum.AMERICA_NEW_DEAL.getChineseName());
                }

                List<UserFile> userFilelist = iUserFileService.list(userFileQueryWrapper);
                if(Collections.EMPTY_LIST.equals(userFilelist)){
                    return R.ok();
                }
                fileIdAndDigestMap = userFilelist.stream().collect(Collectors.toMap(UserFile::getFileId, UserFile::getDigest));

                if(!userFilelist.isEmpty()){
                List<String> fileIds = userFilelist.stream().map(UserFile::getFileId).toList();
                queryWrapper.in("file_id", fileIds);
                }
                fileList = fileService.list(queryWrapper);
            }else {
                QueryWrapper<UserFile> userFileQueryWrapperTwo = new QueryWrapper<>();
                List<UserFile> userFileListTwo = iUserFileService.list(userFileQueryWrapperTwo);
                fileIdAndDigestMap = userFileListTwo.stream().collect(Collectors.toMap(UserFile::getFileId, UserFile::getDigest));
                fileList = fileService.list(queryWrapper);
            }
            List<FileVo> fileVoList = fileList.stream()
                    .map(file -> {
                        FileVo fileVo = new FileVo();
                        file.setFileUrl(file.getFileUrl());
                        BeanUtils.copyProperties(file, fileVo);
                        fileVo.setDigest(fileIdAndDigestMap.get(file.getFileId()));
                        return fileVo;
                    })
                    .collect(Collectors.toList());
            
            return R.ok("文件列表查询成功!", fileVoList);
        } catch (Exception e) {
            log.error("查询文件列表失败", e);
            return R.fail("查询文件列表失败: " + e.getMessage());
        }
    }
}
